<?php

namespace Shahu\Common\common\jwtAuth;

use Shahu\Common\exception\AuthException;
use Shahu\Common\service\AuthService;
use Webman\Http\Request;

class Auth
{
    /**
     * 检查授权
     * @param Request $request
     * @return void
     * @throws AuthException
     */
    public static function checkAuthorization(Request $request) : void
    {
        if (class_exists('app\constant\AuthConstant')) {
            //查找对应的控制器
            $current_pass_arr = \app\constant\AuthConstant::PASS_MAP[$request->controller] ?? [];
            if (!in_array($request->action, $current_pass_arr)) {
                $authorization = $request->header('Authorization', '');
                if (!$authorization) {
                    throw new AuthException("用户未登录");
                }
                $token = str_replace('Bearer ', '', $authorization);
                $user = AuthService::validateToken($token);

                //记录登录信息
                $GLOBALS['user_id'] = $user['id'];
                $GLOBALS['user_name'] = $user['name'];
                $GLOBALS['ip'] = $user['ip'];
            }
        } else {
            throw new AuthException("找不到AuthConstant配置文件");
        }
    }
}
